package com.github.pig.admin.service.zhgl.houseowner.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.mapper.device.GuardDeviceMapper;
import com.github.pig.admin.mapper.zhgl.building.CommunityBuildingMapper;
import com.github.pig.admin.mapper.zhgl.community.CommunityInfoMapper;
import com.github.pig.admin.mapper.zhgl.house.UnitHouseMapper;
import com.github.pig.admin.mapper.zhgl.houseowner.HouseOwnerMapper;
import com.github.pig.admin.model.device.GuardDevice;
import com.github.pig.admin.model.zhgl.building.CommunityBuilding;
import com.github.pig.admin.model.zhgl.house.UnitHouse;
import com.github.pig.admin.model.zhgl.house.UnitHouseBean;
import com.github.pig.admin.model.zhgl.houseowner.CurrentUserBean;
import com.github.pig.admin.model.zhgl.houseowner.HouseOwner;
import com.github.pig.admin.model.zhgl.unit.BuildingUnit;
import com.github.pig.admin.service.zhgl.houseowner.IHouseOwnerService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业主基本信息表 服务实现类
 * </p>
 *
 * @author lxm
 * @since 2018-06-20
 */
@Service
public class HouseOwnerServiceImpl extends ServiceImpl<HouseOwnerMapper, HouseOwner> implements IHouseOwnerService {
    @Autowired
    private HouseOwnerMapper houseOwnerMapper;
    @Autowired
    private UnitHouseMapper unitHouseMapper;
    @Autowired
    private GuardDeviceMapper deviceMapper;
    @Autowired
    private CommunityBuildingMapper buildingMapper;


    @Override
    public Page querHouseOwnerGrid(Page<HouseOwner> page, HouseOwner houseOwner) {
        List<HouseOwner> list = houseOwnerMapper.querHouseOwnerGrid(page,houseOwner);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<UnitHouseBean> queryUnitHouse(UnitHouseBean unithouse) {
        return unitHouseMapper.queryUnitHouseGrid(unithouse);
    }

    @Override
    public UnitHouseBean getUnitHouseBean(String buildingName, String unitName, String houseName, String communityId) {
        return unitHouseMapper.getUnitHouseBean(buildingName,unitName,houseName,communityId);
    }

    @Override
    public CurrentUserBean getCurrentUserAllInfo(String loginName) {
        return houseOwnerMapper.getCurrentUserAllInfo(loginName);
    }

    @Override
    public List<CurrentUserBean> bingCommunityMessage(String loginName) {
        return houseOwnerMapper.bingCommunityMessage(loginName);
    }

    @Override
    public void updateUserType(Integer userId) {
        houseOwnerMapper.updateSysUserType(userId);
    }
    //判断是否超过门禁最大人数限制，如果没有直接更新
    /** 步骤
     * 1、查询添加业主角色
     * 2、角色相对应的设备
     * 3、查询设备总数以及当前人数+1
     * TODO  编辑时，控制当前人数比较困难，可能会多加1
     */
    @Transactional(rollbackFor = Exception.class)
    public List<GuardDevice> isOverLimit(HouseOwner houseOwner) {
        if(StringUtils.isBlank(houseOwner.getRoleId())){
            return null ;
        }
        //1
        String[] rIds = houseOwner.getRoleId().split(",");
        StringBuilder sb = new StringBuilder();
        List<GuardDevice> deviceList = new ArrayList<>();
        for (String rid : rIds){
            //2
            List<GuardDevice> list = deviceMapper.getDeviceId(rid);
            //3
            list.forEach(device ->  {
                if(device.getUserMax()!=null && device.getUserMax()<(device.getUserNow()==null?1:device.getUserNow()+1)){
                    deviceList.add(device);
                }else{
                    sb.append(device.getId()+",");
                }
            });
        }
        //更新所有设备的当前用户数
        if(deviceList==null || deviceList.size()==0){
            deviceMapper.updateUserSumByIds(sb.substring(0,sb.length()-1),1);
        }
        return deviceList;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson invitation(HouseOwner houseOwner) {
        AjaxJson json=new AjaxJson();
        CommunityBuilding building = buildingMapper.selectByHouseId(houseOwner.getHouseId());
        if(CommonConstant.BUILDING_TYPE_ZHUZHAI.equals(building.getBuildingType())){
            //判断当前户人数是否大于10
            EntityWrapper wrapper = new EntityWrapper();
            wrapper.eq("house_id",houseOwner.getHouseId());
            wrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
            Integer count = houseOwnerMapper.selectCount(wrapper);
            if(count>10){
                json.setSuccess(false);
                json.setMsg("邀请家属失败,当前邀请人数已到达上限。");
                return  json;
            }
        }

        //判断是否超过门禁最大人数限制
        List<GuardDevice> devices = this.isOverLimit(houseOwner);
        if(devices!=null && devices.size()>0) {
            StringBuilder sb =  new StringBuilder();
            devices.forEach(device->{
                sb.append(device.getDeviceName());
                sb.append(",");
            });
            json.setSuccess(false);
            json.setMsg("邀请失败,设备："+sb.substring(0,sb.length()-1)+" 容量已经超出上限，详细问题请联系物业。");
            return  json;
        }
        //默认业主本人
        if( this.insert(houseOwner)){
            json.setSuccess(true);
            json.setMsg("添加成功。");
        }else{
            json.setSuccess(false);
            json.setMsg("添加失败。");
        }
        return json;
    }

    /**
     * 撤销人
     * @param houseOwner
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson delInvitation(HouseOwner houseOwner) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        json.setMsg("撤销成功。");
        this.updateById(houseOwner);
        if (StringUtils.isBlank(houseOwner.getRoleId())) {
            return json;
        }
        String[] rIds = houseOwner.getRoleId().split(",");
        StringBuilder sb = new StringBuilder();
        for (String rid : rIds) {
            //获取所有的设备
            List<GuardDevice> list = deviceMapper.getDeviceId(rid);
            list.forEach(device -> {
                sb.append(device.getId() + ",");
            });
        }
        //更新所有设备的当前用户数
        deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), -1);
        return json;
    }
}
